// TODO获取词库
$(function () {
  fetch("/js/data.json")
    .then((response) => response.json()) // 解析JSON响应
    .then((response) => {
      textData = response.data;
    })
    .catch((error) => console.error("Error:", error));
});

/**
 * @constant box 容器
 * @variate place 文字分散在容器中的随机位置
 * @variate textData 文字库集合
 * @variate verifyWord 需要校验的词组，用于渲染布局
 * @constant minVerifyWordLen 随机文字最小数量
 * @variate verifyText 需要校验的随机文字，用于展示
 * @variate verifyTextIdxs 需要校验的文本，取verifyText的index值
 * @variate verifyClickCount 点击校验文字的次数，达到verifyTextIdxs长度进行校验
 * @variate selectedIdxs 选中文字的index集合
 */

const box = $("#box");
let place = [
  { left: "0px", top: "0px" },
  { left: "120px", top: "0px" },
  { left: "240px", top: "0px" },
  { left: "0px", top: "90px" },
  { left: "120px", top: "90px" },
  { left: "240px", top: "90px" },
];

let textData = [];
let verifyWord = "";
const minVerifyWordLen = 3;
let verifyText = "";
let verifyTextIdxs = [];
let verifyClickCount = 0;
let selectedIdxs = [];

/**
 * @function getVerifyWord 获取随机校验词组
 */

function getVerifyWord() {
  return textData[Math.floor(Math.random() * (textData.length - 1))];
}

/**
 * @function getVerifyText 获取随机校验文字
 */
function getVerifyText() {
  // 随机选取校验文字数量
  let lenRandom = Math.ceil(Math.random() * verifyWord.length);
  if (lenRandom < minVerifyWordLen) {
    lenRandom = minVerifyWordLen;
  }

  const verifyArray = verifyWord.split("");
  const result = [];

  // 获取随机需要校验的文字
  for (let i = 0; i < lenRandom; i++) {
    let index = Math.floor(Math.random() * verifyArray.length);
    result.push(verifyArray[index]);
    verifyArray.splice(index, 1); // 移除已选的元素以避免重复
  }

  return result.join("");
}

/**
 * @function getVerifyText 获取校验文字的idx
 */
function getVerifyTextIdxs() {
  const wordArray = verifyWord.split("");
  const textArray = verifyText.split("");
  const result = [];

  for (let text of textArray) {
    const idx = wordArray.findIndex((word) => word === text);
    result.push(idx);
  }

  return result;
}

/**
 * @function clear 重置
 */
function clear() {
  box.empty();
  verifyWord = getVerifyWord();
  verifyText = getVerifyText();
  verifyTextIdxs = getVerifyTextIdxs();
  verifyClickCount = 0;
  selectedIdxs = [];

  $("#resultBox").html(`请依次点击: <span>${verifyText}</span>`);

  place.sort(() => {
    return Math.random() - 0.5;
  });
}

/**
 * @function init 初始化
 */
function init() {
  // 重置内容
  clear();

  verifyWord.split("").map((text, idx) => {
    createVerifyBox(text, idx);
  });

  /**
   * 创建存放每个校验文字的容器
   * @param {string} text 文字
   * @param {number} idx 索引
   * @attribute {number} index 文字标签的index值
   * @attribute {string: true | false } judge 判断标签是否被点击
   */
  function createVerifyBox(text, idx) {
    //创建box分割的div容器
    let divEl = $('<div class="item"></div>');
    divEl.css({
      left: place[idx].left,
      top: place[idx].top,
    });

    //创建span标签存储校验文字
    let spanEl = $(`<span class="spanEl">${text}</span>`);
    divEl.append(spanEl);
    box.append(divEl);

    addSpanElCss(divEl, spanEl);

    // 添加属性，
    // 用于存入selectedIdxs
    spanEl.data("index", idx);
    spanEl.data("judge", "true");
  }

  /**
   * 添加span项样式
   */
  function addSpanElCss(divEl, spanEl) {
    const lt = divEl.width() - spanEl.width() - 10;
    const rt = divEl.height() - spanEl.height() - 10;
    let left = Math.floor(Math.random() * lt);
    let top = Math.floor(Math.random() * rt);
    spanEl.css({
      left: left + "px",
      top: top + "px",
    });
  }

  //span点击事件
  $("#box .item span").click(function (e) {
    if ($(this).data("judge") == "true") {
      selectedIdxs.push($(this).data("index"));
      console.log(selectedIdxs, "selectedIdxs", verifyTextIdxs);
      $(this).data("judge", "false");
      verifyClickCount++;
      appendRadio(e);
      // 验证
      if (verifyClickCount === verifyTextIdxs.length) {
        getVerifyResult();
      }
    }
  });

  //点击事件，生成圆点
  function appendRadio(e) {
    const radioEl = $(`<div class='radio'>${verifyClickCount}</div>`);
    box.append(radioEl);

    const wt = radioEl.width() / 2;
    const ht = radioEl.height() / 2;

    radioEl.css({
      left: e.pageX - box.offset().left - wt + "px",
      top: e.pageY - box.offset().top - ht + "px",
    });
  }
}

/**
 * @function getVerifyResult 获取校验结果
 */
function getVerifyResult() {
  if (selectedIdxs.join() == verifyTextIdxs.join()) {
    $("#resultBox span").html("验证成功");
    $("#resultBox span").css("color", "#1abd6c");
    setTimeout(() => {
      $("#verification").hide();
    }, 500);
    // TODO 验证成功后操作
  } else {
    $("#resultBox span").html("验证失败");
    $("#resultBox span").css("color", "red");
    setTimeout(() => {
      init();
    }, 500);
  }
  verifyClickCount = 0;
}

/**
 * @function 刷新
 */
$(".refresh").click(() => {
  init();
});
